<template>
  <div :class="`tw-libdatepicker x${_uid}`">
    <label v-if="title"
      class="tw-libdatepicker-label">{{title}}:</label>
    <div class="tw-libdatepicker-data">
      <el-date-picker :class="{xerror: errText}"
        v-model="val"
        :type="datetype"
        :align="align"
        :unlink-panels="unlinkpanels"
        :range-separator="rangeseparator"
        :placeholder="placeholder"
        :start-placeholder="splaceholder"
        :end-placeholder="eplaceholder"
        :picker-options="pickerOptions"
        :format="format"
        :value-format="valueformat"
        :size="size"
        :disabled="valdisabled"
        :clearable="clearable"
        :time-arrow-control="timearrowcontrol"
        @change="changeValue"
        @blur="blurValue"
        :default-time="defaulttime"
        >
      </el-date-picker>
    <div v-if="validValue && errText" class="tw-validinput-err">{{errText}}</div>
    </div>
  </div>
</template>

<script>
import props from './props'

export default {
  name: 'libdatepicker',

  props,

  data () {
    return {
      val: '',
      valdisabled: false,
      errText: ''
    }
  },

  methods: {
    blurValue () {
      this.validData('blur')
    },
    changeValue () {
      if (this.validData('change')) {
        this.$emit('input', this.val)
        this.$emit('change', this.val)
      }
    },
    validData (now) {
      let vm = this
      let errText = ''

      if (this.validValue && this.validRules.length > 0) {
        this.validRules.forEach((itm) => {
          let trigger = itm.trigger || 'blur'
          if (now === trigger) {
            if (itm.required !== undefined && itm.required && !vm.val) {
              errText = itm.message
            }
          }
        })
      }

      vm.errText = errText
      return !errText
    },

    setStyle () {
      let style = `
        .tw-libdatepicker.x${this._uid} .el-input__inner {
          width: ${this.width};
          color: ${this.color};
          background-color: ${this.bgColor};
          border-color: ${this.borderColor};
        }
        .tw-libdatepicker.x${this._uid} .el-input.is-active .el-input__inner, .tw-libdatepicker.x${this._uid} .el-input__inner:focus {
          border-color: ${this.focusBorderColor};
        }

        .x${this._uid} .tw-libdatepicker-label {
          width: ${this.labelWidth};
          line-height: ${this.titleHeight};
          font-weight: ${this.titleWeight};
        }

        .x${this._uid} .el-input__inner.is-disabled {
          background-color: #F5F7FA;
          border-color: #E4E7ED;
          color: #C0C4CC;
        }
      `

      if (this.validValue) {
        style += `
          .x${this._uid} .tw-libdatepicker-label::before {
            content: "*";
            color: #f56c6c;
            margin-right: 4px;
          }

          .x${this._uid} .el-input.xerror .el-input__inner {
            border-color: #f56c6c;
          }
        `
      }

      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/\n/g, '')

      document.head.appendChild(styleEl)
    },
    disValue () {
      this.valdisabled = this.disabled
      if (this.validRules.length > 0) {
        this.validRules.forEach((itm) => {
          if (itm.disabled !== undefined && itm.disabled) {
            this.valdisabled = itm.disabled
          }
        })
      }
    }
  },

  computed: {
    style () {
      return {
        color: this.color,
        bgColor: this.bgColor,
        borderColor: this.borderColor,
        focusBorderColor: this.focusBorderColor
      }
    },
    defaulttime () {
      if (this.defaultime) {
        return this.defaultime.split(',')
      } else {
        return null
      }
    },
    pickerOptions () {
      if (this.usePickerOption) {
        if (this.pickerOption !== '' && typeof this.pickerOption === 'function') {
          return this.pickerOption()
        } else {
          return { // 供参考
            disabledDate(time) {
              return time.getTime() > Date.now();
            },
            shortcuts: [{
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
              }
            }, {
              text: '昨天',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24);
                picker.$emit('pick', date);
              }
            }, {
              text: '一周前',
              onClick(picker) {
                const date = new Date();
                date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', date);
              }
            }]
            // shortcuts: [{
            //   text: '本月',
            //   onClick (picker) {
            //     picker.$emit('pick', [new Date(), new Date()])
            //   }
            // }, {
            //   text: '今年至今',
            //   onClick (picker) {
            //     const end = new Date()
            //     const start = new Date(new Date().getFullYear(), 0)
            //     picker.$emit('pick', [start, end])
            //   }
            // }, {
            //   text: '最近六个月',
            //   onClick (picker) {
            //     const end = new Date()
            //     const start = new Date()
            //     start.setMonth(start.getMonth() - 6)
            //     picker.$emit('pick', [start, end])
            //   }
            // }]
          }
        }
      } else {
        return null
      }
    }
  },

  mounted () {
    this.val = this.value
    this.disValue()
    this.setStyle()
  },

  watch: {
    value: {
      deep: true,
      handler () {
        this.val = this.value
      }
    },
    validRules: {
      deep: true,
      handler () {
        this.disValue()
      }
    },

    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
